//#include <iostream>
#include <stack>
#include <map>
#include <vector>
#include <fstream>
#include <stdio.h>
using namespace std;

#define PRINT_HEAD(i) printf("CASE %d:[",(i))
#define PRINT_TAIL() printf("]\n");
typedef struct
{
	char from;
	char to;
}node;
#define MAXLEN 10

vector<char> seq;
map<char,char> op;
map<char,node> comb;
int cases;
char combStr[4];
char opStr[3];
char seqStr[MAXLEN];
int opNum,combNum,seqLen;
bool isInComb(char a,char b,char & tmp)
{
	printf("com size:%d\n",comb.size());
	printf("a=%c;b=%c\n",a,b);
	if(comb.find(a)->second.from == b)
	{
		tmp = comb[a].to;
		printf("true");
		return true;
	}
	if(comb[b].from == a)
	{
		tmp = comb[b].to;
		printf("true2");
		return true;
	}
	printf("false");
	return false;
}
void merge()
{

	if(seq.size() < 2)
		return ;
	printf("size:%d",seq.size());
	printf("seq1:%c;seq2:%c\n",seq[seq.size()-2],seq.back());
	char tmpChar;// = seq.back();
	//combine
	while(seq.size() > 1 &&
			isInComb(seq[seq.size()-2],seq.back(),tmpChar))
	{
		seq.erase(seq.end() -1 );
		seq.push_back(tmpChar);
		printf("comb\n");
	}	

	if(seq.size() < 2)
		return;	
	tmpChar = seq.back();
	vector<char>::iterator i = seq.end()-2;
	while(i != seq.begin())
	{
		if(op[tmpChar] == *i ||
				op[*i] == tmpChar)
		{
			seq.clear();
			printf("op\n");
			return;
		}

		i--;
	}
}
void handle()
{
	for(int i=0;i<seqLen;++i)
	{
		seq.push_back(seqStr[i]);
		merge();
		printf("insert %c\n",seqStr[i]);
	}
}
void init()
{

	seq.clear();
	op.clear();
	comb.clear();
	memset(combStr,0,sizeof(combStr));
	memset(opStr,0,sizeof(opStr));
	memset(seqStr,0,sizeof(seqStr));
	opNum = 0;
	combNum = 0;
	seqLen = 0;
}
int main(int argv,char ** args)
{
	if(argv < 2)
		return 1;
	
	ifstream cin(args[1]);
	if(!cin.is_open())
		return 1;
	cin>>cases;
	for(int i=0;i<cases;++i)
	{
		init();
		cin>>combNum;
		while(combNum--)
		{
			cin>>combStr;
			node n;
			n.from = combStr[1];
			n.from = combStr[2];
			comb.insert(pair<char,node>(combStr[0],n));
		}
		cin>>opNum;
		while(opNum--)
		{
			cin>>opStr;
			op.insert(pair<char,char>(opStr[0],opStr[1]));
		}
		cin>>seqLen;
		cin>>seqStr;
		handle();
		PRINT_HEAD(i+1);
		for(int j=0;j< seq.size();j++)
		{
			printf("%c,",seq[j]);
		}
		PRINT_TAIL();
	}
	return 0;
}
